<?php
namespace Swork\Server\Rpc;

use Swork\Exception\RpcException;

/**
 * RPC接收处理器
 * Class RpcReceive
 * @package Swork\Server\Rpc
 */
class RpcReceive
{
    /**
     * @var \swoole_server
     */
    private $server;

    /**
     * 全局环境变量
     * @var array
     */
    private $env;

    /**
     * Request constructor.
     * @param \swoole_server $server
     * @param array $env
     */
    public function __construct(\swoole_server $server, array $env)
    {
        $this->server = $server;
        $this->env = $env;
    }

    /**
     * RPC处理器
     * @param int $fd
     * @param int $from_id
     * @param string $cmd
     * @param mixed $data
     * @return mixed
     * @throws
     */
    function handler(int $fd, int $from_id, string $cmd, $data)
    {
        //解析执行
        $result = null;
        switch ($cmd)
        {
            case 'srv':
                $result = $this->processService($fd, $data);
                break;
            default :
                throw new RpcException("Invalid cmd [$cmd]");
                break;
        }

        // 返回
        return $result;
    }

    /**
     * 处理远程调用的服务
     * @param int $fd
     * @param $data
     * @return mixed
     * @throws
     */
    private function processService(int $fd, $data)
    {
        return RpcService::process($data);
    }
}
